import os
import datetime

from django.core.files.storage import FileSystemStorage
from django.db.models import Q
from django.shortcuts import render
from langchain.chains.llm import LLMChain
from langchain.chains.sequential import SimpleSequentialChain
from langchain.chains.transform import TransformChain
from langchain_community.document_loaders import TextLoader
from langchain_community.llms.tongyi import Tongyi
from langchain_core.prompts import PromptTemplate
from langchain_text_splitters import CharacterTextSplitter
from rest_framework.generics import ListAPIView
from rest_framework.viewsets import ModelViewSet
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.pagination import PageNumberPagination
from rest_framework.filters import SearchFilter

from doctor.bdapi import bdapi
from doctor.models import TitleModel, MajorModel, DepartmentModel, SubMajorModel, DoctorModel, StatusModel, \
    RemoteConsultationModel, RemoteConsultationModel1
from doctor.serializers import TitleSerializer, MajorSerializer, DepartmentSerializer, SubMajorSerializer, \
    DoctorSerializer, StatusSerializer, RemoteConsultationSerializer, RemoteConsultationModelSerializer1, \
    RemoteConsultationModelSerializer2
from p4demo import settings


class TitleView(ModelViewSet):
    queryset = TitleModel.objects.all()
    serializer_class = TitleSerializer
    lookup_field = "id"
    lookup_url_kwarg = "id"


class MajorView(ModelViewSet):
    queryset = MajorModel.objects.all()
    serializer_class = MajorSerializer
    lookup_field = "id"
    lookup_url_kwarg = "id"


class DepartmentView(ModelViewSet):
    queryset = DepartmentModel.objects.all()
    serializer_class = DepartmentSerializer
    lookup_field = "id"
    lookup_url_kwarg = "id"


class SubMajorView(ModelViewSet):
    queryset = SubMajorModel.objects.all()
    serializer_class = SubMajorSerializer
    lookup_field = "id"
    lookup_url_kwarg = "id"


class pagination(PageNumberPagination):
    page_size = 1
    max_page_size = 4
    page_query_param = 'page'
    page_size_query_param = 'size'


class DoctorView(ModelViewSet):
    queryset = DoctorModel.objects.all()
    serializer_class = DoctorSerializer
    lookup_field = "id"
    lookup_url_kwarg = "id"

    pagination_class = pagination

    def get_queryset(self):
        query = Q()
        name = self.request.query_params.get("name")

        if name:
            query &= Q(name__contains=name)

        return self.queryset.filter(query)


class GetDoctor(ListAPIView):
    queryset = DoctorModel.objects.all()
    serializer_class = DoctorSerializer
    # filter_backends = [SearchFilter]
    # search_fields = ["name"]
    pagination_class = pagination

    def get_queryset1(self):
        query = Q()
        name = self.request.query_params.get("name")

        if name:
            query &= Q(name__contains=name)

        return self.queryset.filter(query)

    def get_queryset(self):
        queryset = DoctorModel.objects.all()
        d_id = self.request.query_params.get("department_id")
        if d_id != '0':
            queryset = queryset.filter(department_id=d_id)
        return queryset


# class DoctorList(APIView):
#     def get(self, request):
#         user = request.query_params.get("name")
#         data = DoctorModel.objects.filter(name__contains=user).first()
#         DoctorModel.objects.filter(name__contains=user).delete()
#         data.avatar = request.data.get("avatar")
#         ret = DoctorSerializer(data=data)
#         if ret.is_valid():
#             ret.save()


# class DoctorList(APIView):
#     def get(self, request):
#         queryset = DoctorModel.objects.all()
#         serializer = DoctorSerializer(queryset, many=True)
#         return Response(serializer.data)


# Create your views here.

# 会诊状态
class StatusView(ModelViewSet):
    queryset = StatusModel.objects.all()
    serializer_class = StatusSerializer
    lookup_field = "id"
    lookup_url_kwarg = "id"


# 远程会诊
class RemoteConsultationView(ModelViewSet):
    queryset = RemoteConsultationModel.objects.all()
    serializer_class = RemoteConsultationSerializer
    lookup_field = "id"
    lookup_url_kwarg = "id"

    pagination_class = pagination

    def get_queryset(self):
        query = Q()
        name = self.request.query_params.get("name")
        major = self.request.query_params.get("major")
        title = self.request.query_params.get("title")
        country_code = self.request.query_params.get("country_code")
        print(country_code)
        print('11111111111111111111111111')
        print(type(country_code))

        if name:
            query &= Q(name__contains=name)
        if major:
            query &= Q(major=int(major))
        if title:
            query &= Q(title=int(title))
        if country_code:
            query &= Q(county_code=country_code)
        return self.queryset.filter(query)


class RemoteConsultationModelView1(ModelViewSet):
    queryset = RemoteConsultationModel1.objects.all()
    serializer_class = RemoteConsultationModelSerializer1
    lookup_field = "id"
    lookup_url_kwarg = "id"


# 查询会诊记录
class GetRemoteConsultationModelView1(APIView):
    def get(self, request):
        data = RemoteConsultationModel1.objects.all()
        ser = RemoteConsultationModelSerializer2(data, many=True)
        return Response(ser.data)


from doctor.FaissDbUtils import FaissDbUtils


# 上传
class upload(APIView):
    def post(self, request):
        print("11111")
        file = request.FILES.get('file')
        print(file)
        filename = file.name  # 文件名
        # 保存文件
        path = os.path.join(settings.MEDIA_ROOT, datetime.datetime.now().strftime('%Y-%m-%d'))
        fs = FileSystemStorage(location=path)
        fs.save(filename, file)

        doc = TextLoader(f"{path}/{filename}", encoding="utf-8").load()
        spliter = CharacterTextSplitter(separator="\n", chunk_size=1000, chunk_overlap=0)
        chunks = spliter.split_documents(doc)

        db = FaissDbUtils()
        db.add(chunks, keyindex="rengong")

        # 添加到数据库
        # add_faiss(f"{path}/{filename}")
        return Response({"code": 200, "msg": "上传成功"})


class dorag(APIView):
    def post(self, request):
        ask = request.data.get("ask")
        db = FaissDbUtils()
        rs = db.search("rengong", ask, count=3)

        prompt = "根据以下内容,回答用户问题.用户的问题是:" + ask + "\n,内容是:"
        if rs:
            for r in rs:
                prompt = prompt + r.page_content + "\n"
            print("提示词:" + prompt)
        llm = Tongyi()
        rs = llm.invoke(prompt)
        return Response({"code": 200, "msg": "大模型处理成功", "data": rs})


def jiaoyan(inputs: dict) -> dict:
    txt = inputs['text']
    rs = bdapi.audit_mes(txt)
    return {"output_text": rs}


class dofabu(APIView):
    def post(self, request):
        content = request.data.get('content')
        print(content+"1111111111111111111111111111")
        transform_chain = TransformChain(
            transform=jiaoyan,
            input_variables=["text"],
            output_variables=["output_text"]
        )
        template = """对下面的内容进行处理,内容是:{a1}:如果内容不合法,则返回这几个字既可.如果内容合法,对该内容进行优化后,返回"""
        prompt = PromptTemplate(
            input_variables=["a1"],
            template=template,
        )

        llm_chain = LLMChain(
            llm=Tongyi(),
            prompt=prompt,
        )

        simple_chain = SimpleSequentialChain(
            chains=[transform_chain, llm_chain],
            verbose=True
        )

        rs = simple_chain.invoke(content)

        return Response({"code": 200, "data": rs})


